<?php
namespace app\admin\controller;

use app\admin\model\Applet as AppletModel;
use think\facade\Cache;
use think\facade\View;

/**
 * 小程序管理控制器
 */
class Applet extends Controller
{
    /**
     * 全部小程序列表
     */
    public function all()
    {
        return $this->lists(0,'全部');
    }
	
	/**
     * 已授权列表
     */
    public function normal()
    {
        return $this->lists(10,'已授权');
    }
	
	/**
     * 已到期列表
     */
    public function ends()
    {
        return $this->lists(20,'已到期');
    }

    /**
     * 获取列表
     */
    private function lists($type, string $title)
    {
        $model = new AppletModel;
        $list = $model->getList($type);
        return View::fetch('index', compact('list','title'));
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = new AppletModel;
         if ($model->remove($id)) {
            return $this->renderSuccess('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
    }

    /**
     * 管理员执行小程序登录
     */
    public function oneKey($id)
    {   
        $model = AppletModel::getApplet(['applet_id' => $id]);
        if ($url = $model->login()) {
            return redirect($url);
        }
        return $this->renderError('登录失败');  
    }

    /**
     * 变更到期时间
     */
    public function genewal($id)
    {
        $model = AppletModel::getApplet(['applet_id' => $id]);
        if ($model->genewal($this->postData('data'))) {
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 发布小程序新模板
     */
    public function upgrade($id)
    {
        //详情
        $model = AppletModel::getApplet(['applet_id' => $id]);
        if($model->publish()){
            return $this->renderSuccess('发布成功');
        }
        $error = $model->getError() ?: '发布失败';
        return $this->renderError($error);
    }

}
